<template>
  <div>
    <el-dialog
      class="custom-dialog"
      v-model="dialogVisible"
      :title="title"
      width="800px"
      @close="handleClose"
    >
      <el-form
        class="data-form"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="所属园区" prop="parkId">
              <el-select
                class="data-input"
                v-model="form.parkId"
                placeholder="请选择"
                @change="handleChangeParkId"
              >
                <el-option
                  v-for="(item, index) of parkOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.pkid"
                  :disabled="item.enable === '0'"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="关联房屋" prop="houseIds">
              <el-select
                class="data-input"
                v-model="form.houseIds"
                placeholder="请选择"
                multiple
                clearable
              >
                <el-option
                  v-for="(item, index) of houseOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.pkid"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="区域名称" prop="name">
              <el-input
                class="data-input"
                v-model="form.name"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="区域描述">
              <el-input
                class="data-input"
                v-model="form.remark"
                placeholder="请输入"
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否重点区域" prop="keyArea">
              <el-radio-group v-model="form.keyArea">
                <el-radio
                  v-for="(item, index) of dict['yn']"
                  :key="index"
                  :value="item.value"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">
          关联设备序列号
          <el-button type="primary" @click="handleAdd">关联设备</el-button>
        </div>
        <el-table class="custom-table" :data="form.deviceList">
          <el-table-column prop="name" label="设备名称" />
          <el-table-column prop="code" label="设备序列号" />
          <el-table-column prop="location" label="设备位置" />
          <el-table-column prop="status" label="设备状态">
            <template #default="scope">
              <el-tag :type="getDictStyle('device_status', scope.row.status)">{{
                getDictValue('device_status', scope.row.status)
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="操作" width="100">
            <template #default="scope">
              <el-button type="danger" link @click="handleRemove(scope)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <el-button @click="handleClose(false)" :loading="loading"
          >取消</el-button
        >
        <el-button type="primary" @click="handleSubmit" :loading="loading"
          >确定</el-button
        >
      </template>
    </el-dialog>
    <DeviceDialog ref="deviceDialogRef" @change="handleChangeDevice" />
  </div>
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDict } from '@/hooks/useDict'
const { dict, getDictStyle, getDictValue } = useDict(['yn'])
import {
  keyAreaAdd,
  keyAreaUpdate,
  keyAreaDetail,
} from '@/api/manager/dataManage/keyAreaManage.js'
import { parkPageList } from '@/api/manager/dataManage/park'
import { buildingPageList } from '@/api/manager/dataManage/building'
import DeviceDialog from './components/deviceDialog.vue'
defineOptions({
  name: 'AddDialog',
})
const props = defineProps({
  detail: {
    type: Object,
  },
})
watch(
  () => props.detail,
  async () => {
    if (props.detail.pkid && dialogVisible.value) {
      handleDetail()
    }
  },
)
const handleDetail = async () => {
  const res = await keyAreaDetail({ pkid: props.detail.pkid })
  if (res.success) {
    // 处理房屋
    res.data.houseIds = res.data.houseList.map((i) => {
      return i.pkid
    })
    delete res.data.houseList
    // 处理设备
    res.data.deviceList = res.data.equipmentInfos
    delete res.data.equipmentInfos
    form.value = { ...res.data }
    initHouseOptions()
  } else {
    ElMessage.error(res.message)
  }
}
const emit = defineEmits(['close'])
const title = ref('')
const dialogVisible = ref(false)
const handleClose = (isFlash) => {
  form.value = { keyArea: '1', deviceList: [] }
  formRef.value.clearValidate()
  dialogVisible.value = false
  emit('close', isFlash)
}
const formRef = ref(null)
const form = ref({
  keyArea: '1',
  deviceList: [],
})
const rules = ref({
  parkId: [{ required: true, message: '请选择所属园区', trigger: 'blur' }],
  keyArea: [{ required: true, message: '请选择是否重点区域', trigger: 'blur' }],
  name: [{ required: true, message: '请输入区域名称', trigger: 'blur' }],
})

const loading = ref(false)
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      const params = JSON.parse(JSON.stringify(form.value))
      // 处理房屋
      params.houseIds = params.houseIds ? params.houseIds.join(',') : ''
      // 处理设备
      params.equipmentIds = params.deviceList
        .map((i) => {
          return i.pkid
        })
        .join(',')
      delete params.deviceList

      try {
        let res
        if (form.value.pkid) {
          res = await keyAreaUpdate(params)
        } else {
          res = await keyAreaAdd(params)
        }
        if (res.success) {
          ElMessage.success('保存成功')
          handleClose(true)
        } else {
          ElMessage.error(res.message)
        }
        loading.value = false
      } catch (error) {
        console.log('error', error)
        loading.value = false
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}
const parkOptions = ref([])
const initParkList = async () => {
  const res = await parkPageList({ pageIndex: 1, pageSize: 9999 })
  parkOptions.value = res.data.list
}
const handleChangeParkId = () => {
  form.value.houseId = ''
  initHouseOptions()
}

const deviceDialogRef = ref()
const handleAdd = () => {
  deviceDialogRef.value.multipleSelection = JSON.parse(
    JSON.stringify(form.value.deviceList),
  )
  deviceDialogRef.value.dialogVisible = true
}
const handleRemove = (scope) => {
  form.value.deviceList.splice(scope.$index, 1)
}
const handleChangeDevice = (val) => {
  form.value.deviceList = JSON.parse(JSON.stringify(val))
}

const houseOptions = ref([])
const initHouseOptions = async () => {
  const res = await buildingPageList({
    pageIndex: 1,
    pageSize: 9999,
    parkId: form.value.parkId,
  })
  houseOptions.value = res.data.list
}
defineExpose({ dialogVisible, title })
onMounted(() => {
  initParkList()
})
</script>
<style lang="scss" scoped>
.title {
  font-size: 16px;
  line-height: 30px;
  font-weight: 500;
  color: #151515;
  margin-bottom: 20px;
  position: relative;
  padding-left: 10px;

  &::before {
    content: ' ';
    position: absolute;
    left: 0;
    top: 7px;
    width: 4px;
    height: 16px;
    background: linear-gradient(0deg, #4575ee 0%, #6297f5 100%);
    border-radius: 2px;
  }
  .el-button {
    margin-left: 25px;
  }
}
</style>
